package com.shareware.common.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.shareware.common.DEFAULT
import com.shareware.common.appFontScale
import com.shareware.common.delegate.Preference

/**
 * desc: 功能描述
 * email: mobiledeveloper@qq.com
 */
object ActivityExt {

    private var appFirstInstalled: Boolean by Preference("app.install", true, PREFERENCE_SETTING)
    private val allActivities: MutableList<Activity> = ArrayList()
    private val exitAllActivityNotifies = HashSet<Runnable>()
    private var appFirstStart = true
    val lifecycleCallbacks = InnerLifecycleCallbacks()
    var appFirstInstall = appFirstInstalled
        private set

    /**
     * 存活的Activity数量
     */
    private var activityAliveCount = 0


    fun getNetChangeImpl(): List<Activity> {
        return allActivities.filter { it is INetChangeProtocol }
    }

    /**
     * @return 存活的Activity数量
     */
    fun getActivityAliveCount(): Int {
        return activityAliveCount;
    }

    fun finishAllActivity() {
        allActivities.forEach {
            it.finish()
        }
        allActivities.clear()
        activityAliveCount = 0
        NetConnectService.release()
    }

    /**
     * 获取Activity
     *
     * @return activity
     */
    fun getTopActivity(): Activity? {
        if (allActivities.isEmpty()) {
            return null
        }
        val size = allActivities.size - 1
        for (index in size downTo 0) {
            val activity = allActivities[index]
            if (activity.isFinishing || activity.isDestroyed) {
                break
            }
            return activity
        }
        return null
    }

    /**
     * finish指定Activity
     *
     * @param cls activity
     */
    fun assignActivityExit(cls: Class<*>) {
        val iterator = allActivities.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (cls == activity.javaClass) {
                iterator.remove()
                activity.finish()
            }
        }
    }

    /**
     * 注册App退出事件
     */
    fun registerAppExitListener(runnable: Runnable) {
        exitAllActivityNotifies.add(runnable)
    }

    class InnerLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
        val eventTimestamp = hashMapOf<Int, Long>()
        private var activityStartCount = 0
        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            activity.resources.displayMetrics.scaledDensity =
                activity.resources.displayMetrics.density * appFontScale
            ++activityAliveCount
            allActivities.add(activity)
            if (eventTimestamp.isNotEmpty()) {
                eventTimestamp.clear()
            }
            if (appFirstStart) {
                appFirstStart = false
                if (appFirstInstall) {
                    appFirstInstalled = false
                }
                log(DEFAULT, "当前App环境:$appEnvironment")
                if (appPrivacyHasGrant()) {
                    tryMethodIgnore {
                        Class.forName("com.shareware.oaid.OaIdGenerator").newInstance()
                    }
                }
            }
        }

        override fun onActivityStarted(activity: Activity) {
            activityStartCount++
        }

        override fun onActivityResumed(activity: Activity) {
            appBackground = false
        }

        override fun onActivityPaused(activity: Activity) = Unit

        override fun onActivityStopped(activity: Activity) {
            activityStartCount--
            if (activityStartCount == 0) {
                appBackground = true
            }
        }

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit

        override fun onActivityDestroyed(activity: Activity) {
            val iterator = allActivities.iterator()
            while (iterator.hasNext()) {
                if (iterator.next() == activity) {
                    iterator.remove()
                    break
                }
            }
            if (--activityAliveCount <= 0) {
                appExit()
            }
        }

        fun appExit() {
            exitAllActivityNotifies.forEach { it.run() }
        }
    }
}